﻿using IOC.Desgin;
using ORM.DB;
using ORM.Model;
using ORM.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ORM.Base
{
    public class Record
    {
        private string DefaultConnectString = "Base_ConnectionString";
        private string _ConnectStringName;
        public string OptionID { set; get; }
        public bool IsExist { set; get; }
        public bool TraceSQL { set; get; }
        public string ConnectStringName
        {
            set
            {
                _ConnectStringName = value;
                _DBHelper = new DBHelper(ConnectStringName);
            }
            get
            {
                return _ConnectStringName;
            }
        }
        public string TableName { set; get; }
        public string KeyFieldName { set; get; }
        public string KeyFieldValue { set; get; }
        public string SQL { set; get; }
        public Hashtable RecordResult { set; get; }
        public Hashtable RecordParams { set; get; }
        private DBHelper _DBHelper { set; get; }
        public DbTransaction Transition { set; get; }

        public object this[string ColumnName]
        {
            set
            {
                if (RecordParams.Contains(ColumnName))
                {
                    RecordParams[ColumnName] = value;
                }
                else
                {
                    RecordParams.Add(ColumnName, value);
                }

            }
            get
            {
                return RecordResult[ColumnName];
            }
        }

        public Record()
        {

        }

        public Record(string TableName)
        {
            this.TableName = TableName;
            this.ConnectStringName = DefaultConnectString;
            RecordResult = new Hashtable();
            RecordParams = new Hashtable();
            TraceSQL = false;
        }

        public Record(string TableName, string ConnectStringName)
        {
            this.TableName = TableName;
            this.ConnectStringName = ConnectStringName;
            RecordResult = new Hashtable();
            RecordParams = new Hashtable();
            TraceSQL = false;
        }

        public Record(string TableName, string KeyFiledName, string KeyFieldValue)
        {
            this.TableName = TableName;
            this.KeyFieldName = KeyFiledName;
            this.KeyFieldValue = KeyFieldValue;
            this.ConnectStringName = DefaultConnectString;
            RecordResult = new Hashtable();
            RecordParams = new Hashtable();
            if (KeyFieldName != null && !RecordParams.ContainsKey(KeyFieldName))
            {
                RecordParams.Add(KeyFieldName, KeyFieldValue);
            }
            TraceSQL = false;

        }


        public Record(string TableName, string KeyFiledName, string KeyFieldValue, string ConnectStringName)
        {
            this.TableName = TableName;
            this.KeyFieldName = KeyFiledName;
            this.KeyFieldValue = KeyFieldValue;
            this.ConnectStringName = ConnectStringName;
            RecordResult = new Hashtable();
            RecordParams = new Hashtable();
            if (KeyFieldName != null && !RecordParams.ContainsKey(KeyFieldName))
            {
                RecordParams.Add(KeyFieldName, KeyFieldValue);
            }
            TraceSQL = false;

        }

        public void Init(string ConnectStringName = "Base_ConnectionString")
        {
            this.ConnectStringName = ConnectStringName;
            RecordResult = new Hashtable();
            RecordParams = new Hashtable();
            if (KeyFieldName != null && !RecordParams.ContainsKey(KeyFieldName))
            {
                RecordParams.Add(KeyFieldName, KeyFieldValue);
            }
            TraceSQL = false;

        }


        [InterceptAttibute]
        public virtual void Query()
        {
            List<Param> Params = new List<Param>();
            Param param = new Param();
            param.ParamName = KeyFieldName;
            param.ParamValue = KeyFieldValue;
            Params.Add(param);
            DataTable dt = _DBHelper.ExecuteQuery(SQL, Params);
            if (dt.Rows.Count > 0)
            {
                foreach (DataColumn column in dt.Columns)
                {
                    if (!RecordResult.Contains(column.ColumnName))
                    {
                        RecordResult.Add(column.ColumnName, dt.Rows[0][column.ColumnName]);
                    }
                    else
                    {
                        RecordResult[column.ColumnName] = dt.Rows[0][column.ColumnName];
                    }
                }
                IsExist = true;
            }
            else
            {
                IsExist = false;
            }

        }
        [InterceptAttibute]
        public virtual void Execute()
        {
            if (KeyFieldName != null && !RecordParams.ContainsKey(KeyFieldName))
            {
                RecordParams.Add(KeyFieldName, KeyFieldValue);
            }
            List<Param> Params = new List<Param>();
            foreach (DictionaryEntry de in RecordParams)
            {
                Param param = new Param();
                param.ParamName = de.Key.ToString();
                param.ParamValue = de.Value;
                Params.Add(param);
            }
            if (Transition == null)
            {
                _DBHelper.ExecuteSQL(SQL, Params);
            }
            else
            {
                _DBHelper.ExecuteSQL(Transition, SQL, Params);
            }

        }

        public void ClearParams()
        {
            RecordParams.Clear();
        }

        public void Trace(int TotalMilliseconds)
        {
            LogUtil.WriteLog("ORMTrace", "RecordTraceLog", "执行时间：" + TotalMilliseconds + Environment.NewLine);
            LogUtil.WriteLog("ORMTrace", "RecordTraceLog", "sql语句：" + SQL + Environment.NewLine);
            string paramsstr = string.Empty;
            foreach (DictionaryEntry item in RecordParams)
            {
                paramsstr += "name：" + item.Key.ToString() + "/value：" + Convert.ToString(item.Value) + Environment.NewLine;
            }
            LogUtil.WriteLog("ORMTrace", "RecordTraceLog", "sql语句对应参数：" + paramsstr);
            LogUtil.WriteLog("ORMTrace", "RecordTraceLog", "====================================================================" + Environment.NewLine);
        }

        public void TraceOverTime(int TotalMilliseconds)
        {
            LogUtil.WriteLog("ORMTrace", "OverTimeTraceLog", "执行时间：" + TotalMilliseconds + Environment.NewLine);
            LogUtil.WriteLog("ORMTrace", "OverTimeTraceLog", "拦截来源：Record,sql语句：" + SQL + Environment.NewLine);
            string paramsstr = string.Empty;
            foreach (DictionaryEntry item in RecordParams)
            {
                paramsstr += "name：" + item.Key.ToString() + "/value：" + Convert.ToString(item.Value) + Environment.NewLine;
            }
            LogUtil.WriteLog("ORMTrace", "OverTimeTraceLog", "sql语句对应参数：" + paramsstr);
            LogUtil.WriteLog("ORMTrace", "OverTimeTraceLog", "====================================================================" + Environment.NewLine);
        }

        private bool IsRowExist()
        {
            SQLBuilder sqlbuilder = new SQLBuilder();
            string sql = sqlbuilder.BuildRecordSQL(this, Enum.SQLType.EXIST);
            List<Param> Params = new List<Param>();
            Param param = new Param();
            param.ParamName = KeyFieldName;
            param.ParamValue = KeyFieldValue;
            Params.Add(param);
            return Convert.ToInt32(_DBHelper.ExecuteScar(sql, Params)) > 0 ? true : false;
        }

    }
}
